package entity;

public class EPatternRegister extends ERegister {
	private String value;
	private String textValue;
	private long registerValue = -1l;
	private EPattern[] patterns;
	
	public EPatternRegister(String name, int address, String dataType,
			String description, String unit, EPattern[] patterns) {
		super(name, address, dataType, description, false, unit);
		this.patterns = patterns;
	}
	
	public String getTextValue() {
		return textValue;
	}
	
	public String getTextValue(long val)
	{
		String textValue  = ""; 
		for (int i = 0; i < patterns.length; i++) 
		{
			if (checkMask(val, patterns[i].pattern,patterns[i].base)) 
			{
				if (textValue.equalsIgnoreCase("")) {
					textValue += patterns[i].text;
				} else {
					textValue += "\n" + patterns[i].text;
				}
			}
		}
		
		return textValue;
	}

	@Override
	public Object getValue() {
		return value;
	}

	@Override
	public void setValue(byte b0, byte b1, byte b2, byte b3) {
		String registerString = "";
		
		String byteString = Integer.toBinaryString(b3);
		try {
			registerString += byteString.substring(byteString.length()-8);
		} catch (IndexOutOfBoundsException e) {
			registerString += "00000000".substring(byteString.length()) + byteString;
		}
		byteString = Integer.toBinaryString(b2);
		try {
			registerString += byteString.substring(byteString.length()-8);
		} catch (IndexOutOfBoundsException e) {
			registerString += "00000000".substring(byteString.length()) + byteString;
		}
		byteString = Integer.toBinaryString(b1);
		try {
			registerString += byteString.substring(byteString.length()-8);
		} catch (IndexOutOfBoundsException e) {
			registerString += "00000000".substring(byteString.length()) + byteString;
		}
		byteString = Integer.toBinaryString(b0);
		try {
			registerString += byteString.substring(byteString.length()-8);
		} catch (IndexOutOfBoundsException e) {
			registerString += "00000000".substring(byteString.length()) + byteString;
		}
		
		this.value = registerString;
		long newValue = Long.parseLong(registerString,2);
		if (newValue != registerValue) {
			registerValue = newValue;
			textValue = "";
			for (int i = 0; i < patterns.length; i++) {
				if (checkMask(registerValue, patterns[i].pattern,patterns[i].base)) {
					if (textValue.equalsIgnoreCase("")) {
						textValue += patterns[i].text;
					} else {
						textValue += "; " + patterns[i].text;
					}
					
				}
			}
			
			setChanged();
			notifyObservers(value);
		}
	}

	private boolean checkMask(long val, String mask, int base) {
		return (((Long.parseLong(mask.replace('X', '1'), base) & val) == val) &&
				((~Long.parseLong(mask.replace('X', '0'), base) & ~val) == ~val));
	}
        
    @Override
        public String toString(){
            return "\"" + value + "\"";     
        }

}
